package com.xmu.prcs.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.xmu.prcs.action.bean.SubjectBean;
import com.xmu.prcs.action.bean.UserInfoBean;
import com.xmu.prcs.service.UserManager;
import com.xmu.prcs.util.DictionaryUtil;
import com.xmu.prcs.util.PageBean;
import com.xmu.prcs.util.ResultBean;

/**
 * 用户
 * @author frequent
 * @version 1.0,2012-3-20
 *
 */
@SuppressWarnings("serial")
public class UserAction extends BaseAction{

	private UserManager userManager;
	
	private UserInfoBean user;
	
	private int userId;
	
	private ResultBean userPage;
	
	private List<UserInfoBean> userlist;
	
	/**
	 * 界面上显示的页码
	 */
	private List<String> pageNumber;
	
	/**
	 * 与界面交互的分页封装类
	 */
	private PageBean page = new PageBean();
	
	/**
	 * 处理结果，冻结或解冻
	 */
	private int userResult;
	
	/**
	 * 分页时的最后一页
	 */
	private String endPage;
	
	/**
	 * 翻页
	 * -1表示向前翻页
	 * 0表示不翻页
	 * 1表示向后翻页
	 */
	private int move = 0;
	
	private String userName;
	
	/**
	 * 上传的文件
	 */
	private File upload;
	
	/**
	 * 上传的文件名
	 */
	private String uploadFileName;
	
	/**
	 * 上传的文件类型
	 */
	private String uploadContentType;

	public UserManager getUserManager() {
		return userManager;
	}

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
	public UserInfoBean getUser() {
		return user;
	}

	public void setUser(UserInfoBean user) {
		this.user = user;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public ResultBean getUserPage() {
		return userPage;
	}

	public void setUserPage(ResultBean userPage) {
		this.userPage = userPage;
	}

	public List<UserInfoBean> getUserlist() {
		return userlist;
	}

	public void setUserlist(List<UserInfoBean> userlist) {
		this.userlist = userlist;
	}

	public List<String> getPageNumber() {
		return pageNumber;
	}

	public void setPageNumber(List<String> pageNumber) {
		this.pageNumber = pageNumber;
	}

	public PageBean getPage() {
		return page;
	}

	public void setPage(PageBean page) {
		this.page = page;
	}

	public int getUserResult() {
		return userResult;
	}

	public void setUserResult(int userResult) {
		this.userResult = userResult;
	}

	public int getMove() {
		return move;
	}

	public void setMove(int move) {
		this.move = move;
	}

	public String getEndPage() {
		return endPage;
	}

	public void setEndPage(String endPage) {
		this.endPage = endPage;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	/**
	 * 查看个人信息
	 * @return
	 */
	public String showUserInfo(){
		Integer userId = (Integer)this.getSession().getAttribute("userId");
		System.out.println("userId:" + userId);
		user = userManager.getUserById(userId.toString());
		return SUCCESS;
	}
	
	/**
	 * 跳转到修改用户信息页面
	 * @return
	 */
	public String toModifyUserInfo(){
		Integer userId = (Integer)this.getSession().getAttribute("userId");
		System.out.println("userId:" + userId);
		user = userManager.getUserById(userId.toString());
		return SUCCESS;
	}
	
	/**
	 * 修改用户信息
	 * @return
	 */
	public String modifyUserInfo(){
		Integer userId = (Integer)this.getSession().getAttribute("userId");
		System.out.println("userId:" + userId);
		String fileName = uploadImage();//上传头像
		if(!fileName.equals("")){
			fileName.replace('\\', '/');
		}
		user.setPhoto(fileName);
		userManager.modifyUserInfo(userId, user);
		return SUCCESS;
	}
	
	 /** 
     * 上传单个图片，返回图片存储文件名
     * @return 
     */  
    public String uploadImage(){  
    	if(upload == null || uploadFileName == null || uploadFileName.equals("")){
    		return DictionaryUtil.DEFAULT_PHOTO;
    	}
    	
    	try {
    		
    		String basePath = this.getRequest().getSession().getServletContext().getRealPath("") + "\\";
    		String storeFileName = this.createNewFileName();
    		String fileName = basePath + storeFileName;
    		String backup = "d:\\" + storeFileName; //备份位置
    		//防止文件名重复
    		int add = 1;
    		while(new File(fileName).exists()){
    			fileName += add;
    			add++;
    		}
			FileOutputStream fos = new FileOutputStream(fileName);
			FileOutputStream backupfos = new FileOutputStream(backup);
			InputStream is = new FileInputStream(upload);//页面传进来的文件
			byte[] buffer = new byte[8192]; //每次读写8K字节
			int count = 0;
			while((count = is.read(buffer)) > 0){
				fos.write(buffer, 0, count);
				backupfos.write(buffer, 0, count);
			}
			fos.close();
			backupfos.close();
			is.close();
			return storeFileName;
		}catch(NullPointerException e){
			e.printStackTrace();
			return DictionaryUtil.DEFAULT_PHOTO;
		}
    	catch (FileNotFoundException e) {
			e.printStackTrace();
			return DictionaryUtil.DEFAULT_PHOTO;
		} catch (IOException e) {
			e.printStackTrace();
			return DictionaryUtil.DEFAULT_PHOTO;
		}
    }  
    
    /**
     * 得到新的文件名
     * @return
     */
    public String createNewFileName(){
    	Date date = new Date();
    	String basePath = this.getRequest().getSession().getServletContext().getRealPath("") + "\\";
    	File filedir = new File(basePath + DictionaryUtil.UPLOAD_PLANT_IMAGE_PATH);
    	if(!filedir.exists()){
    		filedir.mkdir();
    	}
    	String filename = DictionaryUtil.UPLOAD_FILE_PATH + "img";
    	filename += date.getTime();
    	System.out.println("uploadfilename:" + upload.getName());
    	System.out.println("name:" + uploadFileName);
    	System.out.println("type:" + uploadContentType);
    	//获得上传文件的后缀名
    	filename += uploadFileName.substring(uploadFileName.indexOf("."));
    	return filename;
    }
    
    /**
     * 冻结用户
     * @return
     */
    public String freezeUser(){
    	userManager.freezeUser(userId);
    	this.listUsers();
    	userResult = 2;
    	return SUCCESS;
    }
    
    /**
     * 解冻用户
     * @return
     */
    public String unfreezeUser(){
    	userManager.unfreezeUser(userId);
    	this.listUsers();
    	userResult = 1;
    	return 	SUCCESS;
    }
    
    public String listUsers(){
    	if(move == 1){
    		if(Integer.parseInt(endPage) == 0 ){
    			page.setCurrentPage(page.getCurrentPage() + 9);
    		}
    	}else if(move == -1){
    		if(page.getCurrentPage() > 9){
    			page.setCurrentPage(page.getCurrentPage() - 9);
    		}
    	}
    	
    	userPage = userManager.listUsers4page(page, userName);
    	userlist = (List<UserInfoBean>)userPage.getContent();
    	
    	//处理界面显示页码，从当前页码开始
    	pageNumber = new ArrayList<String>();
    	if(userPage.getPage().getCountPage() - userPage.getPage().getCurrentPage() + 1 <= 10){//最多显示10个页码
    		for(int i = userPage.getPage().getCurrentPage() ; i <= userPage.getPage().getCountPage(); i++){
    			System.out.println(i);
    			pageNumber.add(Integer.toString(i));
    		}
    	}else{
    		for(int i = userPage.getPage().getCurrentPage(); i < userPage.getPage().getCurrentPage() + 9; i++){
    			pageNumber.add(Integer.toString(i));
    		}
    		pageNumber.add("0");//表示省略号
    		pageNumber.add(Integer.toString(userPage.getPage().getCountPage()));
    	}
    	
    	userResult = 0;
    	return SUCCESS;
    }
    
    /**
     * 查看用户
     * @return
     */
    public String checkUserInfo(){
    	System.out.println("userId:" + userId);
		user = userManager.getUserById(Integer.toString(userId));
    	return SUCCESS;
    }
}
